import { defineStore } from 'pinia'
import { ref } from 'vue'
import { apiGetHotelDetail, apiGetHotelReviews, apiGetHotelLocation } from '@/api/api'
import { message } from 'ant-design-vue'

export interface HotelRoom {
  id: number
  name: string
  capacity: number
  size: number
  price: number
  bedType: string
  image?: string
  imageUrl?: string
  gallery?: string[]
  galleryUrls?: string[]
  tags: string[]
  amenities: Array<{ name: string, icon: any }> | string[]
  description?: string
}

export interface HotelReview {
  id: number
  author: string
  avatar: string
  content: string
  rating: number
  date: string
  roomType: string
  images?: string[]
}

export interface HotelLocation {
  id?: string
  latitude: number
  longitude: number
  address: string
  city?: string
  country?: string
  postalCode?: string
  province?: string
  transportation?: any[]
  attractions?: any[]
}

export interface AmenityCategory {
  id: string
  name: string
  iconName: string
  items: AmenityItem[]
}

export interface AmenityItem {
  id: string
  name: string
  iconName: string
  available: boolean
  priceValue?: number
  priceFormat?: string
  price?: string
}

export interface HotelAmenities {
  id: string
  categories: AmenityCategory[]
}

export interface HotelPolicy {
  id: string
  checkInTime: string
  checkOutTime: string
  minAdvanceReservation?: number
  maxAdvanceReservation?: number
  freeCancellationHours?: number
  cancellationFeePercent?: number
  paymentMethods: string[]
  prepaymentRequired?: boolean
  prepaymentPercent?: number
  petsAllowed?: boolean
  petFee?: number
  childrenAllowed?: boolean
  childAgeThreshold?: number
  extraBedAllowed?: boolean
  extraBedFee?: number
}

export interface HotelDetail {
  id: number | string
  name: string
  rating: number
  address: string
  city: string
  phone: string
  mainImage: string
  description: string
  rooms: HotelRoom[]
  reviews: HotelReview[]
  location: HotelLocation | null
  amenities: HotelAmenities | null
  policy: HotelPolicy | null
}

export const useHotelDetailStore = defineStore('hotelDetail', () => {
  // 酒店详情数据
  const hotelDetail = ref<HotelDetail>({
    id: '',
    name: '',
    rating: 0,
    address: '',
    city: '',
    phone: '',
    mainImage: '',
    description: '',
    rooms: [],
    reviews: [],
    location: null,
    amenities: null,
    policy: null
  })

  // 加载状态
  const loading = ref({
    basic: false,
    rooms: false,
    reviews: false,
    location: false,
    amenities: false,
    policy: false
  })

  // 获取酒店详细信息
  const fetchHotelDetail = async (hotelId: string | number) => {
    loading.value.basic = true
    loading.value.rooms = true
    loading.value.amenities = true
    loading.value.policy = true
    loading.value.location = true
    
    try {
      const res: any = await apiGetHotelDetail(hotelId)
      if (res && res.code === 200 && res.data) {
        // 获取基本信息
        const basicInfo = res.data.basic || {}
        
        // 更新酒店基本数据
        hotelDetail.value = {
          ...hotelDetail.value,
          id: hotelId,
          name: basicInfo.name || '未命名酒店',
          rating: basicInfo.rating || 0,
          address: basicInfo.address || '',
          city: basicInfo.city || '',
          description: basicInfo.description || '',
          phone: basicInfo.phone || '',
          mainImage: basicInfo.avatar || '',
        }
        
        // 如果有房间信息，更新房间数据
        if (res.data.rooms && res.data.rooms.length > 0) {
          hotelDetail.value.rooms = res.data.rooms.map((room: any) => {
            return {
              id: room.id,
              name: room.name,
              capacity: room.capacity || 2,
              size: room.size || 35,
              price: room.price || 888,
              bedType: room.bedType || '特大床',
              image: room.image || room.imageUrl || '',
              imageUrl: room.imageUrl || '',
              gallery: room.gallery || room.galleryUrls || [],
              galleryUrls: room.galleryUrls || [],
              tags: room.tags || ['高层', '禁烟'],
              amenities: room.amenities ? 
                (typeof room.amenities[0] === 'string' ? 
                  room.amenities : 
                  room.amenities.map((a: string) => ({ name: a, icon: null }))
                ) : 
                [{ name: '免费WiFi', icon: null }, { name: '空调', icon: null }],
              description: room.description || ''
            }
          })
        }
        
        // 如果有设施信息，更新设施数据
        if (res.data.amenities) {
          hotelDetail.value.amenities = res.data.amenities
        }
        
        // 如果有位置信息，更新位置数据
        if (res.data.location) {
          hotelDetail.value.location = res.data.location
        }
        
        // 如果有政策信息，更新政策数据
        if (res.data.policy) {
          hotelDetail.value.policy = res.data.policy
        }
        
        return true
      } else {
        message.error('获取酒店信息失败')
        return false
      }
    } catch (error) {
      console.error('获取酒店信息失败:', error)
      message.error('获取酒店信息失败')
      return false
    } finally {
      loading.value.basic = false
      loading.value.rooms = false
      loading.value.amenities = false
      loading.value.policy = false
      loading.value.location = false
    }
  }

  // 获取酒店评论
  const fetchHotelReviews = async (hotelId: string | number, page = 1, pageSize = 10) => {
    loading.value.reviews = true
    try {
      const res: any = await apiGetHotelReviews(hotelId, page, pageSize)
      if (res && res.code === 200) {
        // 适配后端返回的分页数据结构
        // 预期后端返回格式: { records: HotelReview[], total: number, ... }
        if (res.data && typeof res.data === 'object') {
          // 如果是分页对象
          if (res.data.records) {
            const reviewsArray = res.data.records || [];
            
            hotelDetail.value.reviews = reviewsArray.map((review: any) => {
              return {
                id: review.id,
                author: review.username || '匿名用户',
                avatar: review.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${review.id}`,
                content: review.content || '',
                rating: review.rating || 5,
                date: review.createTime || new Date().toISOString().split('T')[0],
                roomType: review.roomType || '标准房',
                images: review.images || []
              }
            });
            
            // 返回完整的分页数据，让组件可以获取总数等信息
            return res.data;
          } 
          // 如果是数组（兼容旧格式）
          else if (Array.isArray(res.data)) {
            hotelDetail.value.reviews = res.data.map((review: any) => {
              return {
                id: review.id,
                author: review.username || '匿名用户',
                avatar: review.avatar || `https://api.dicebear.com/7.x/avataaars/svg?seed=${review.id}`,
                content: review.content || '',
                rating: review.rating || 5,
                date: review.createTime || new Date().toISOString().split('T')[0],
                roomType: review.roomType || '标准房',
                images: review.images || []
              }
            });
            
            // 返回模拟的分页数据
            return {
              records: hotelDetail.value.reviews,
              total: hotelDetail.value.reviews.length,
              pages: 1,
              current: 1,
              size: hotelDetail.value.reviews.length
            };
          }
        }
        
        return {
          records: [],
          total: 0,
          pages: 0,
          current: 1,
          size: pageSize
        };
      } else {
        console.warn('获取酒店评论失败');
        return {
          records: [],
          total: 0,
          pages: 0,
          current: 1,
          size: pageSize
        };
      }
    } catch (error) {
      console.error('获取酒店评论失败:', error);
      return {
        records: [],
        total: 0,
        pages: 0,
        current: 1,
        size: pageSize
      };
    } finally {
      loading.value.reviews = false;
    }
  }

  // 获取酒店位置信息 - 由于详情API已经包含位置信息，此方法可能不再需要
  const fetchHotelLocation = async (hotelId: string | number) => {
    loading.value.location = true
    try {
      const res: any = await apiGetHotelLocation(hotelId)
      if (res && res.code === 200 && res.data) {
        hotelDetail.value.location = res.data
        return true
      } else {
        console.warn('获取酒店位置信息失败')
        return false
      }
    } catch (error) {
      console.error('获取酒店位置信息失败:', error)
      return false
    } finally {
      loading.value.location = false
    }
  }

  // 加载所有酒店相关数据
  const loadAllHotelData = async (hotelId: string | number) => {
    try {
      const detailResult = await fetchHotelDetail(hotelId)
      if (detailResult) {
        // 如果需要额外加载评论，可以在这里调用
        await fetchHotelReviews(hotelId)
      }
      return detailResult
    } catch (error) {
      console.error('加载酒店数据失败:', error)
      return false
    } finally {
      // 确保所有loading状态都被重置
      loading.value.basic = false
      loading.value.rooms = false
      loading.value.amenities = false
      loading.value.policy = false
      loading.value.location = false
      loading.value.reviews = false
    }
  }

  // 重置状态
  const resetState = () => {
    hotelDetail.value = {
      id: '',
      name: '',
      rating: 0,
      address: '',
      city: '',
      phone: '',
      mainImage: '',
      description: '',
      rooms: [],
      reviews: [],
      location: null,
      amenities: null,
      policy: null
    }
    loading.value = {
      basic: false,
      rooms: false,
      reviews: false,
      location: false,
      amenities: false,
      policy: false
    }
  }

  return {
    hotelDetail,
    loading,
    fetchHotelDetail,
    fetchHotelReviews,
    fetchHotelLocation,
    loadAllHotelData,
    resetState
  }
})
